from aiohttp import ClientSession
from aiosmtplib import SMTP
from contextlib import closing
from email.header import Header
from email.mime.text import MIMEText
from requests import request
from socket import AF_INET, SOCK_STREAM, socket
from urllib.parse import urlparse


async def async_http_requests(method, url, **kwargs):
    async with ClientSession() as session:
        async with session.request(method, url, **kwargs) as response:
            try:
                json_data = await response.json()
            except Exception as exp:
                text_data = await response.text()
                raise TypeError(exp, text_data)
            else:
                return json_data


async def async_send_email(uri, email, subject, content):
    results = urlparse(uri)
    message = MIMEText(content, "plain", "utf-8")
    message["From"], message["To"] = results.username, email
    message["Subject"] = Header(subject, "utf-8")
    async with SMTP(hostname=results.hostname, port=results.port, use_tls=True) as smtp:
        await smtp.login(message["From"], results.password)
        return await smtp.send_message(message)


def checker_tcp_address(tcp_address):
    host_schema = urlparse(tcp_address)
    with closing(socket(AF_INET, SOCK_STREAM)) as sock:
        return sock.connect_ex((host_schema.hostname, host_schema.port)) == 0


def http_requests(method, url, **kwargs):
    with request(method, url, **kwargs) as response:
        try:
            return response.json()
        except Exception as exp:
            raise TypeError(exp, response.text)
